#include "support.h"
#include <QVector>
#include <QRgb>
#include <QDebug>
#include <sstream>

QImage MatToQImage(const cv::Mat &mat)
{
	if (mat.type() == CV_8UC3)
	{
		QImage image = QImage(mat.cols, mat.rows, QImage::Format_RGB888);
		image.fill(0);

		int step = mat.cols * 3;

		for (int j = 0; j < mat.rows; ++j)
		{
			uchar *qline = image.scanLine(j);
			uchar * const * cvline = mat.ptr<uchar*>(j);

			std::memcpy(qline, cvline, step);
		}

		return image;
	}
	else if (mat.type() == CV_8UC1)
	{
		QImage image = QImage(mat.cols, mat.rows, QImage::Format_Indexed8);
		//color table
		QVector<QRgb> colorTable;
		for (int i = 0; i < 256; ++i)
		{
			colorTable.push_back(qRgb(i,i,i));
		}
		image.setColorTable(colorTable);
		image.fill(0);

		int step = mat.cols;
		for (int j = 0; j < mat.rows; ++j)
		{
			uchar *qline = image.scanLine(j);
			uchar * const * cvline = mat.ptr<uchar*>(j);

			std::memcpy(qline, cvline, step);
		}
		
		return image;

	}
	else
	{
		return QImage();
	}
}

void printMat(const cv::Mat &mat)
{
	std::ostringstream oss;
	oss << mat;
	qDebug() << QString::fromStdString(oss.str());	
}
